#!/bin/sh

# Usage:
# `record`: Ask for recording type via dmenu
# `record screencast`: Record both audio and screen
# `record video`: Record only screen
# `record audio`: Record only audio
#
# If there is already a running instance, user will be prompted to end it.

DMENU="dmenu"

updateicon() { \
	echo "$1" > /tmp/recordingicon
	pkill -RTMIN+9 "${STATUSBAR:-dwmblocks}"
}

killrecording() {
	recpid="$(cat /tmp/recordingpid)"
	# kill with SIGTERM, allowing finishing touches.
	kill -15 "$recpid"
	rm -f /tmp/recordingpid
	updateicon ""
	pkill -RTMIN+9 "${STATUSBAR:-dwmblocks}"
	sleep 3
	kill -9 "$recpid"
	exit
}

screencast() { \
	ffmpeg -y \
	-f x11grab \
	-framerate 30 \
	-s "$(xdpyinfo | grep dimensions | awk '{print $2;}')" \
	-i "$DISPLAY" \
	-f pulse -i default \
	-r 30 \
	-c:v h264 -crf 0 -preset ultrafast -c:a aac \
	-threads 2 \
	"$HOME/vid/scr/screencast-$(date '+%y%m%d-%H%M-%S').mp4" &
	echo $! > /tmp/recordingpid
	updateicon "ﲟ"
}

video() { \
	ffmpeg \
	-f x11grab \
	-draw_mouse 1 \
	-framerate 30 \
	-s $(xdpyinfo | grep dimensions | awk '{print $2;}') \
	-i :0.0+0,0 \
	-c:v libx264 -pix_fmt yuv420p -preset veryfast -q:v 1 \
	-threads 2 \
	"$HOME/vid/scr/video-$(date '+%y%m%d-%H%M-%S').mp4" &
	echo $! > /tmp/recordingpid
	updateicon ""
}

audio() { \
	ffmpeg \
	-f pulse -i default \
	-c:a flac \
	"$HOME/vid/audio-$(date '+%y%m%d-%H%M-%S').flac" &
	echo $! > /tmp/recordingpid
	updateicon ""
}

askrecording() { \
	[ -f /tmp/recordingpid ] && asktoend && exit
	choice=$(printf "screencast\\nvideo\\naudio" | $DMENU -p "Record:")
	case "$choice" in
		screencast) screencast;;
		video) video;;
		audio) audio;;
	esac
}

asktoend() { \
	response=$(printf "no\\nyes" | $DMENU -p "End Recording:") &&
	[ "$response" = "yes" ] &&  killrecording
}

case "$1" in
	screencast) screencast;;
	audio) audio;;
	video) video;;
	kill) killrecording;;
	*) askrecording;;
esac
